<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Parent</title>
    <script src="../../dist/post-message-bus.umd.js"></script>
</head>

<body>
    <div>
        <input type="text" id="value" />
        <button id="sync">同步到iframe</button>
    </div>
    <ol id="log"></ol>
    <script>
        var log = msg => {
            const node = document.createElement("li");
            document.querySelector("#log").appendChild(node);
            node.textContent = msg;
            console.log(`[${location.pathname}] `, msg);
        }
    </script>
    <script>
        var bus1 = PostMessageBus.generateBusToFrame("child1.html", {
            echo: function (from, req) {
                log(`received echo ${from}`);
                return req.getName().then(name => `Hello ${name}`);
            }
        });
        document.body.append(bus1.frame);
        var req1 = null;
        bus1.then(({ request }) => {
            req1 = request;
            log("child1.html is ready");
        });

        var bus2 = PostMessageBus.generateBusToFrame("child2.html", {
            echo: function (from, req) {
                log(`received echo ${from}`);
                return req.getName().then(name => `Hello ${name}`);
            }
        });
        document.body.append(bus2.frame);
        var req2 = null;
        bus2.then(({ request }) => {
            req2 = request;
            log("child2.html is ready");
            request.sendDate(new Date().toISOString()).then(() => {
                log(`child has received date`);
            });
        });

        document.getElementById("sync").addEventListener("click", function () {
            const value = document.getElementById("value").value;
            req1.changeValue(value).then(val => console.log(val));
            req2.updateValue(value).then(val => console.log(val));
        });
    </script>
</body>

</html>